<template>
  <div class="login">
    <el-card>
      <el-form
        :model="submitForm"
        :rules="submitRules"
        label-position="left"
        label-width="80px"
        ref="submitForm"
      >
        <el-form-item label="用户名:" prop="userName">
          <el-input placeholder="请输入用户名" v-model="submitForm.userName" />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input placeholder="请输入密码" v-model="submitForm.password" />
        </el-form-item>
      </el-form>
      <div style="display:flex;justify-content:space-between">
        <el-button type="primary" @click="login">登 录</el-button>
        <router-link to="/register"
          ><el-button type="text">注 册</el-button></router-link
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "login",
  data() {
    return {
      submitForm: {
        userName: "",
        password: ""
      },
      submitRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    login() {
      this.$refs["submitForm"].validate(async valid => {
        if (valid) {
          const {
            data: { errno, message, data }
          } = await axios.post("/api/user/login", this.submitForm);
          if (!errno) {
            this.$message({ type: "success", message: "登录成功" });
            this.$store.commit("setUsers", data);
            this.$store.commit("setIsLogin", true);
            this.$router.push({ path: "/userInfo" });
          } else {
            this.$message({ type: "error", message });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
}
</style>
